Skip to main content
This guide covers the complete inference pipeline for OpenCLIP models, from loading to computing image-text similarities.

Quick Start

Complete Inference Pipeline

1

Load Model and Preprocessing

Load the model with appropriate precision and device settings:
2

Prepare Inputs

Preprocess images and tokenize text:
3

Encode Image and Text

Extract features using the model:
4

Normalize and Compute Similarity

Normalize features and compute cosine similarity:

Encoding Methods

Image Encoding

The encode_image() method:
  • Accepts tensors of shape [batch, 3, height, width]
  • Returns normalized embeddings of shape [batch, embed_dim]
  • embed_dim varies by model (512 for ViT-B, 768 for ViT-L, etc.)

Text Encoding

The encode_text() method:
  • Accepts tokenized text tensors of shape [batch, context_length]
  • Returns embeddings of shape [batch, embed_dim]
  • Texts longer than context_length are truncated

Batch Processing

Processing Multiple Images Efficiently

Processing Large Text Collections

Computing Similarities

Image-to-Text Similarity

Image-to-Image Similarity

Zero-Shot Classification

Optimizations

Mixed Precision Inference

Automatic mixed precision (AMP) can provide 2-3x speedup on modern GPUs with minimal accuracy loss.

Disabling Gradient Computation

Always use torch.no_grad() during inference:
This:
  • Reduces memory usage by ~50%
  • Speeds up computation
  • Prevents accidental gradient computation

Model Compilation (PyTorch 2.0+)

Remember to call model.eval() before inference. Some models use BatchNorm or stochastic depth which behave differently in training vs eval mode.